<template>
    <div>
        <h2>专家预约管理</h2>
        <el-table :data="appointments" style="width: 100%">
            <el-table-column prop="name" label="用户姓名" />
            <el-table-column prop="appointmentTime" label="预约时间" />
            <el-table-column prop="description" label="说明" />
            <el-table-column label="状态">
                <template slot-scope="scope">
                    <el-tag :type="statusType(scope.row.status)">{{ statusText(scope.row.status) }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="备注">
                <template slot-scope="scope">
                    <el-input v-model="scope.row.remark" size="small" placeholder="可填写备注"
                        @change="updateRemark(scope.row)" />
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button v-if="scope.row.status === 'pending'" type="success" size="small"
                        @click="approve(scope.row)">通过</el-button>
                    <el-button v-if="scope.row.status === 'pending'" type="danger" size="small"
                        @click="reject(scope.row)">拒绝</el-button>
                    <el-button v-if="scope.row.status === 'approved'" type="primary" size="small" @click="goChat(scope.row.userId)">聊天</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-empty v-if="!appointments.length" description="暂无预约记录" />
        <el-divider style="margin:40px 0;" />
        <h3>我的个人信息</h3>
        <el-card class="info-card">
            <el-form :model="expertForm" ref="expertForm" label-width="80px" style="max-width:500px;">
                <el-form-item label="头像">
                    <el-upload class="avatar-uploader" action="#" :show-file-list="false" :auto-upload="false"
                        :on-change="handleUpload">
                        <img v-if="expertForm.expert.avatar" :src="'api' + expertForm.expert.avatar" class="avatar" />
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="姓名"><el-input v-model="expertForm.expert.name" /></el-form-item>
                <el-form-item label="邮箱"><el-input v-model="expertForm.expert.email" /></el-form-item>
                <el-form-item label="职称"><el-input v-model="expertForm.expert.title" /></el-form-item>
                <el-form-item label="领域"><el-input v-model="expertForm.expert.field" /></el-form-item>
                <el-form-item label="简介"><el-input v-model="expertForm.expert.description"
                        type="textarea" /></el-form-item>
                <el-form-item label="电话"><el-input v-model="expertForm.expert.phone" /></el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="saveExpertInfo">保存</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-dialog :visible.sync="chatVisible" title="与用户聊天" width="500px">
            <div v-for="msg in chatMessages" :key="msg.id" :style="{ textAlign: msg.fromExpert ? 'right' : 'left' }">
                <span v-if="msg.fromExpert">[我]</span>
                <span v-else>[用户]</span>
                <span>{{ msg.content }}</span>
                <span style="font-size:12px;color:#888;">{{ msg.sendTime }}</span>
            </div>
            <el-input v-model="chatInput" placeholder="请输入内容..." @keyup.enter.native="sendChat" />
            <el-button type="primary" @click="sendChat">发送</el-button>
        </el-dialog>

        <el-dialog title="图片裁剪" :visible.sync="cropperVisible" width="600px" append-to-body
            :close-on-click-modal="false" :close-on-press-escape="false">
            <div class="cropper-content">
                <vue-cropper ref="cropper" :img="cropImage" :info="true" :autoCrop="true" :autoCropWidth="300"
                    :autoCropHeight="300" :fixedBox="true" :fixed="true" :fixedNumber="[1, 1]" :centerBox="true"
                    outputType="png" :full="true" :canMove="true" :canMoveBox="true" :original="false" :enlarge="1">
                </vue-cropper>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cropperVisible = false">取 消</el-button>
                <el-button type="primary" @click="handleCropUpload">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import { getExpertAppointments, updateAppointment } from '../api/ExpertAppointmentController';
import { getExpertDetail, updateExpert } from '../api/ExpertController';
import { connectChatSocket, sendChatMessage, closeChatSocket } from '../api/chatSocket';
import { VueCropper } from 'vue-cropper'
import Request from '@/utils/request';
export default {
    data() {
        return {
            userId: this.getUserIdFromLogin(),
            appointments: [],
            expertForm: {
                user: {},
                expert: {
                    id: '',
                    name: '111',
                    email: '',
                    title: '',
                    field: '',
                    description: '',
                    phone: '',  // 确保所有表单字段都有初始值
                    avatar: ''  // 添加头像字段初始化
                }
            },
            chatVisible: false,
            chatMessages: [],
            chatInput: '',
            currentUserId: null,
            cropperVisible: false,
            cropImage: '',
            uploadFile: null
        };
    },
    components: {
        VueCropper
    },
    methods: {


        handleUpload(file) {
            const isImage = file.raw.type.startsWith('image/');
            const isLt10M = file.raw.size / 1024 / 1024 < 10;

            if (!isImage) {
                this.$message.error('上传文件只能是图片格式!');
                return false;
            }
            if (!isLt10M) {
                this.$message.error('上传图片大小不能超过 10MB!');
                return false;
            }

            this.uploadFile = file.raw;
            const reader = new FileReader();
            reader.readAsDataURL(file.raw);
            reader.onload = () => {
                this.cropImage = reader.result;
                this.cropperVisible = true;
            };
            return false;
        },

        async handleCropUpload() {
            try {
                const blob = await new Promise((resolve) => {
                    this.$refs.cropper.getCropBlob((data) => resolve(data));
                });

                const fileName = `cropped-${Date.now()}.png`;
                const file = new File([blob], fileName, { type: 'image/png' });

                const formData = new FormData();
                formData.append('file', file);

                const res = await Request.post('/file/upload/img', formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data',
                        'token': this.userInfo?.token
                    }
                });

                if (res.code === '0') {
                    this.expertForm.expert.avatar = res.data;
                    this.$message.success('头像上传成功');
                    this.cropperVisible = false;
                } else {
                    throw new Error(res.msg || '上传失败');
                }
            } catch (error) {
                console.error('图片上传失败:', error);
                this.$message.error(error.message || '图片上传失败');
            }
        },

        getUserIdFromLogin() {
            const user = JSON.parse(localStorage.getItem("backUser") || '{}');

            return user.id || null;
        },
        async loadData() {
            const res = await getExpertAppointments(this.userId);
            console.log(res);
            
            this.appointments = (Array.isArray(res) ? res : (res.data || [])).map(item => ({
                ...item,
                userName: item.userName || (item.user && item.user.name) || '',
                remark: item.remark || ''
            }));

            
        },
        statusText(status) {
            switch (status) {
                case 'pending': return '待审核';
                case 'approved': return '已通过';
                case 'rejected': return '已拒绝';
                case 'cancelled': return '已取消';
                default: return status;
            }
        },
        statusType(status) {
            switch (status) {
                case 'pending': return 'warning';
                case 'approved': return 'success';
                case 'rejected': return 'danger';
                case 'cancelled': return 'info';
                default: return '';
            }
        },
        async approve(row) {
            await updateAppointment({ ...row, status: 'approved' });
            this.$message.success('已通过预约');
            this.loadData();
        },
        async reject(row) {
            await updateAppointment({ ...row, status: 'rejected' });
            this.$message.success('已拒绝预约');
            this.loadData();
        },
        async updateRemark(row) {
            await updateAppointment({ ...row });
            this.$message.success('备注已更新');
        },
        async loadExpert() {
            try {
                const res = await getExpertDetail(this.userId);
                console.log(res);

                this.expertForm = {
                    expert: {
                        name: '',
                        email: '',
                        title: '',
                        field: '',
                        description: '',
                        phone: '',
                        avatar: '',
                        ...(res?.expert || {})
                    }
                };
            } catch (error) {
                console.error('加载专家信息失败:', error);
            }
        },
        async saveExpertInfo() {

            this.expertForm.expert.userId = this.userId;
            // 分别保存 user 和 expert

            await updateExpert(this.expertForm.expert);
            this.$message.success('个人信息已保存');
            this.loadExpert();
        },
        onAvatarSuccess(res, file) {
            // TODO: 实现头像上传逻辑
            this.$message.success('头像上传成功（模拟）');
            this.expertForm.expert.avatar = URL.createObjectURL(file.raw);
        },
        openChat(row) {
            this.currentUserId = row.userId;
            this.chatMessages = [];
            this.chatVisible = true;
            connectChatSocket({
                expertId: this.expertId,
                userId: row.userId,
                role: 'expert',
                onMessage: (msg) => {
                    if (msg.userId == row.userId) this.chatMessages.push(msg);
                }
            });
        },
        sendChat() {
            if (!this.chatInput) return;
            const msg = {
                expertId: this.expertId,
                userId: this.currentUserId,
                content: this.chatInput,
                fromExpert: true,
                sendTime: new Date().toISOString()
            };
            sendChatMessage(msg);
            this.chatMessages.push(msg);
            this.chatInput = '';
        },
        goChat(userId) {
            this.$router.push({ name: 'ExpertChatIM', query: { userId } });
        }
    },
    watch: {
        chatVisible(val) {
            if (!val) closeChatSocket();
        }
    },
    mounted() {
        this.loadData();
        this.loadExpert();
    }
};
</script>
<style scoped>
.avatar {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    object-fit: cover;
    margin-bottom: 10px;
}

.info-card {
    margin-top: 20px;
}

.avatar-uploader {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    overflow: hidden;
    border: 1px dashed #d9d9d9;
    display: flex;
    align-items: center;
    justify-content: center;
}
.avatar-uploader:hover {
    border-color: #409EFF;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
}
.avatar {
    width: 100%;
    height: 100%;
    object-fit: cover;
}
.cropper-content {
    width: 100%;
    height: 400px;
}
</style>